from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import Context
from django.contrib.auth.decorators import login_required
import logging
from hocabul.models import School, Course, Department, UserProfile


#@login_required
def hocabul_main_page(request):
    """
    If users are authenticated, direct them to the main page. Otherwise,
    take them to the login page.
    """
    logging.info( "here")
#    course_list = Course.objects.all()
    c = Context({}) 
    return render_to_response('hocabul/index.html', c)


def delete_course(request, user_id, course_id):
  print("[delete] course %s for user %s" % (course_id, user_id))
  try:
    user = UserProfile.objects.get(id=user_id)
    course = Course.objects.get(id=course_id)
    user.courses.remove(course)
  except Exception, e:
    logging.warn("[delete - failed] course %s for user %s" % (course_id, user_id))
  logging.info("[delete - success] course %s for user %s" % (course_id, user_id))
  return HttpResponse("ok")

def get_courses(request, department_id):
  courses = Department.objects.get(id=department_id).courses.all()
  response = str([{'name':str(course.name), 'id': course.id} for course in courses])
  return HttpResponse(response)


def add_course(request, user_id, course_id):
  logging.info("[add] course %s for user %s" % (course_id, user_id))
  user = UserProfile.objects.get(id=user_id)
  course = Course.objects.get(id=course_id)
  user.courses.add(course)
  return HttpResponse(course.to_json())

def view_profile(request, user_id):
    """
    If users are authenticated, direct them to the main page. Otherwise,
    take them to the login page.
    """
    logging.info("view_profile")
    data = {'users':UserProfile.objects.all()}
    cur_user = UserProfile.objects.get(id=user_id)
    data['cur_user'] = cur_user
    data['courses'] = cur_user.courses.all()
    departments = Department.objects.filter(school = cur_user.school)
    data['departments'] = departments
    c = Context(data) 
    return render_to_response('hocabul/profile.html', c)

def view_courses(request):
    logging.info("view courses")
    school = School.objects.get(id=1)
    return render_to_response('hocabul/base_courses.html', {'departments':Department.objects.filter(school = school)})

def view_course(request, course_id):
    logging.info("view course")
    course = Course.objects.get(id=course_id)
    return render_to_response('hocabul/course.html', {'course':course})
    
def add_lesson(request):
  if 'lesson_name' in request.GET: 
    message = 'You searched for: %r' % request.GET['lesson_name'] 
  else: 
    message = 'You submitted an empty form.' 
  return HttpResponse(message)

